<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索 -->
      <el-row>
        <el-col :span="12"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="pages.query"
              class="input-with-select"
              clearable
              @input="search"
            >
              <el-button
                slot="append"
                @click="getusers"
                icon="el-icon-search"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="4"
          ><div class="grid-content bg-purple-light">
            <el-button type="primary" @click="dialogVisible = true"
              >添加</el-button
            >
          </div></el-col
        >
        <el-col :span="8"><div class="grid-content bg-purple"></div></el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="list" border style="width: 100%; margin-top: 16px">
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="change(scope.row.id, scope.row.mg_state)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              class="el-icon-edit"
              @click="edit(scope.row)"
              type="primary"
              size="small"
            ></el-button>
            <el-button
              type="danger"
              size="small"
              class="el-icon-delete"
              @click="del(scope.row.id)"
            ></el-button>
            <el-button
              type="warning"
              size="small"
              class="el-icon-setting"
              @click="fenp(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pages.pagenum"
        :page-sizes="[3, 5, 6, 7]"
        :page-size="pages.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- <span>这是一段信息</span> -->
      <div>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="ruleForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="ruleForm.mobile"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >立即创建</el-button
            >
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog title="编辑用户" :visible.sync="dialogVisibleedit" width="50%">
      <!-- <span>这是一段信息</span> -->
      <div>
        <el-form
          :model="editruleForm"
          :rules="rules"
          ref="editruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editruleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editruleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editruleForm.mobile"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editok('eidtruleForm')"
              >立即修改</el-button
            >
            <el-button @click="dialogVisibleedit = false">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="dialogVisiblefenp" width="50%">
      <!-- <span>这是一段信息</span> -->
      <div class="leftfenp">
        <div class="d">当前用户：{{ fenpruleForm.username }}</div>
        <div class="d">当前角色：{{ fenpruleForm.role_name }}</div>
        <div class="d">
          分配角色：角色角色的id:{{ fenpei }}
          <el-select v-model="fenpei" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleDesc"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <span>
          <el-button type="primary" @click="fenpok">确定</el-button>
          <el-button @click="dialogVisiblefenp = false">取消</el-button>
        </span>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
import {
  UsersApi,
  AddusersApi,
  ChangestateApi,
  DeluserApi,
  EditusersApi,
  FenpeiApi,
  FenpeiRoleApi
} from '@/http/api'
export default {
  name: 'usersA',
  data() {
    // rule, value, callback  验证规则，对谁进行验证，放行
    // 编写邮箱验证
    const checkemail = (rule, value, callback) => {
      // 邮箱正则
      const reg =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      // 如果不满足就会报错，否则放行
      if (!reg.test(value)) {
        // 报错
        return callback(new Error('邮箱格式不正确，请重新输入'))
      }
      // 放行
      callback()
    }
    // 编写手机号验证规则
    const checkemobile = (rule, value, callback) => {
      const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      if (!reg.test(value)) {
        return callback(new Error('手机号格式不正确，请重新输入'))
      }
      callback()
    }
    return {
      pages: {
        query: '',
        pagenum: 1, // 当前页码
        pagesize: 5 // 每页显示条数
      },
      list: [],
      total: 0, // 总条数
      dialogVisible: false,
      dialogVisibleedit: false,
      dialogVisiblefenp: false, // 分配角色
      // 添加
      ruleForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑
      editruleForm: {
        id: 0,
        username: '',
        email: '',
        mobile: ''
      },
      // 分配
      fenpruleForm: {
        id: 0,
        username: '',
        role_name: ''
      },
      fenpei: '',
      options: [], // 角色数据
      // 验证
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 20, message: '长度在 5 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkemobile, trigger: 'blur' }
        ]
      },
      // 编辑的回填
      editval: {}
    }
  },
  created() {
    this.getusers()
  },
  methods: {
    // 分配
    async fenp(val) {
      this.dialogVisiblefenp = true
      this.fenpruleForm.id = val.id
      this.fenpruleForm.username = val.username
      this.fenpruleForm.role_name = val.role_name
      this.options = await FenpeiApi()
      console.log(this.options)
    },
    async fenpok() {
      if (!this.fenpei) {
        this.$message({
          type: 'error',
          message: '角色ID不能为空'
        })
        return
      }
      console.log(this.fenpei)
      this.dialogVisiblefenp = false
      console.log(this.fenpruleForm.id)
      const data = {
        id: this.fenpruleForm.id,
        rid: this.fenpei
      }
      const res = await FenpeiRoleApi(data)
      this.getusers()
      console.log(res)
      this.fenpei = ''
    },
    // 编辑
    edit(val) {
      this.editval = val
      console.log(val)
      this.dialogVisibleedit = true
      // 回填
      this.editruleForm.id = val.id
      this.editruleForm.username = val.username
      this.editruleForm.email = val.email
      this.editruleForm.mobile = val.mobile
    },
    editok(formName) {
      this.$refs.editruleForm.validate(async (valid) => {
        // 不符合
        if (!valid) return false
        // 符合
        // 调接口，新用户接口
        console.log(this.editruleForm)
        const res = await EditusersApi(this.editruleForm)
        console.log('编辑用户的结果', res)
        this.dialogVisibleedit = false
        this.getusers()
      })
    },
    // 删除
    del(id) {
      console.log(id)

      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await DeluserApi(id)
          console.log(res)
          if (res === null) {
            this.getusers()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 开关状态修改
    async change(uid, type) {
      console.log(uid, type)
      const res = await ChangestateApi(uid, type)
      console.log(res)
      // this.getusers()
    },
    // 搜索
    search: _.debounce(function () {
      this.getusers()
    }, 300),
    // 列表渲染
    async getusers() {
      const res = await UsersApi(this.pages)
      console.log(res)
      this.list = res.users
      this.total = res.total
    },
    // 分页
    handleSizeChange(val) {
      console.log(val)
      this.pages.pagesize = val
      this.getusers()
    },
    handleCurrentChange(val) {
      console.log(val)
      this.pages.pagenum = val
      this.getusers()
    },
    // 添加
    submitForm(formName) {
      this.$refs.ruleForm.validate(async (valid) => {
        // 不符合
        if (!valid) return false
        // 符合
        // 调接口，新用户接口
        const res = await AddusersApi(this.ruleForm)
        console.log('添加用户的结果', res)
        this.dialogVisible = false
        //
        this.getusers()
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.leftfenp {
  text-align: left;
  .d {
    margin-top: 20px;
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>
